# flask网页对话程序， 调用zhipuAI库client.chat.completions.create，
# 用户在网页底部从input栏输入一个问题, 点击提交，使用glm-4-flash模型输出一个回答补全对话，并直接显示在网页上。
# 不显示历史记录，但将所有的问题和回答都保存在sqlite3数据库history.sqlite3内。
# 点击页面的历史记录按钮时，从数据库提取记录显示在当前网页上，再次点击就隐藏历史记录。

from flask import Flask, render_template, request, redirect, url_for
from zhipuai import ZhipuAI
import sqlite3
import os

app = Flask(__name__)

# 创建数据库连接
dir_path = os.path.dirname(os.path.realpath(__file__))
db_path = dir_path + '\history.sqlite3'
# conn = sqlite3.connect('history.sqlite3')
conn = sqlite3.connect(db_path)
c = conn.cursor()

# 创建历史记录表
c.execute('''CREATE TABLE IF NOT EXISTS history
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
             question TEXT,
             answer TEXT)'''
)
c.close()
conn.close()

# 创建ZhipuAI客户端
api_key = "a567d89b7d4f40eea9ae11316558a49e.qqLYnJSsBDYmfIW2"
client = ZhipuAI(api_key=api_key)

@app.route('/')
def index():
    # 从数据库中获取历史记录
    conn = sqlite3.connect(db_path)
    c = conn.cursor()
    c.execute("SELECT * FROM history")
    history = c.fetchall()
    c.close()
    conn.close()
    answer = history[-1][2] if history else ""
    answer = answer.replace("'", "")
    return render_template('index_app6.html', history=history, answer=answer)

@app.route('/submit', methods=['POST'])
def submit():
    # 获取用户输入的问题
    question = request.form['question']
    
    # 使用ZhipuAI的client.chat.completition方法获取回答
    response = client.chat.completions.create(
        model="glm-4-flash",
        messages=[{"role": "user", "content": question}],
        top_p=0.7,
        temperature=0.95,
        max_tokens=1024,
        stream=False
    )
    answer = response.choices[0].message.content
    # 将问题和回答保存到数据库
    conn = sqlite3.connect(db_path)
    c = conn.cursor()
    c.execute("INSERT INTO history (question, answer) VALUES (?, ?)", (question, answer))
    conn.commit()
    c.close()
    conn.close()
    return redirect(url_for('index'))   

@app.route('/clear', methods=['POST'])
def clear():
    # 获取数据库连接
    conn = sqlite3.connect(db_path)
    # 创建游标
    cursor = conn.cursor()
    cursor.execute('DELETE FROM history;')  # 替换'tablename'为你的表名
    conn.commit()
    cursor.close()
    conn.close()
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.run(debug=True)
    
    